package com.hcb.tonguetiphealth.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader.ImageCallBack;
import com.hcb.tonguetiphealth.manager.Exit;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.homepage.RegisterWidget;

//@SuppressLint("ShowToast")
public abstract class GeneralWidget extends FrameLayout{
	private static final String TAG = "GeneralWidget";
	private Activity ctx;
	private Toast toast;
	private ProgressDialog messageDialog;
	private ProgressDialog progressDialog;
	private AsyncBitmapLoader asyncBitmapLoader;
	private String userName = "";
	private String password = "";
	public GeneralWidget(Context context) {
		super(context);
		ctx = (Activity) context;
		asyncBitmapLoader = AsyncBitmapLoader.getInstance();
		toast = Toast.makeText(ctx, "", Toast.LENGTH_LONG);
	}
	
	public abstract void notifyAdapter() ;
	
	protected void mSetContentView(View view) {
		ctx.setContentView(view);
		notifyAdapter();
	}

	protected void showMessage(Context ctx, String msg) {
    	toast.setText(msg);
    	toast.show();
    }
	protected void showMessage(Context ctx, int resId) {
		toast = Toast.makeText(ctx, resId, Toast.LENGTH_LONG);
    	toast.show();
    }
	
	  protected ProgressDialog getProgressDialog() {
	    	if(progressDialog == null) {
	    		progressDialog = new ProgressDialog(ctx);
	    	}
	    	return progressDialog;
	    }
	
	  public void backHome(){
		  ctx.finish();
	  }
	  
	  
	  public void exit(){
		  Exit.close();
	  }
	
	protected void sendMsg(int arg1, Handler handler) {
        if (null != handler) {
            Message msg = handler.obtainMessage();
            msg.arg1 = arg1;
            msg.sendToTarget();
        }
    }
	
	//--------- 圆形进度条对话框 ------------------------------------------------------------
	protected void showMessageDialog(Activity ctx, final String text) {
		dismissMessageDialog();
    	messageDialog = new ProgressDialog(ctx);
        messageDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        messageDialog.setTitle("请稍等");
        //messageDialog.setIcon(R.drawable.smile);
        messageDialog.setMessage(text);
        messageDialog.setCancelable(true);
        messageDialog.setCanceledOnTouchOutside(false);
        messageDialog.show();
    }
    protected void dismissMessageDialog() {
        if (messageDialog != null) {
            messageDialog.dismiss();
        }
    }
    //--------- 长形进度条对话框 ------------------------------------------------------------
    protected void showProgressDialog(Activity ctx, final String text, final int max) {
        progressDialog = new ProgressDialog(ctx);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("请稍等");
        //progressDialog.setIcon(R.drawable.smile);
        progressDialog.setMessage(text);
        progressDialog.setProgress(0);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(max);
        progressDialog.setCancelable(false);
        progressDialog.setOnKeyListener(new android.content.DialogInterface.OnKeyListener(){
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (KeyEvent.KEYCODE_BACK == keyCode) {
					progressDialog.dismiss();
				}
				return false;
			}
        });
        progressDialog.show();
    }
    protected void setDialogProgress(int value) {
        if (progressDialog != null)
            progressDialog.setProgress(value);
    }
    protected void dismissProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }
 
    protected void showOverdueDialog(){
    	final Builder mDialog = new AlertDialog.Builder(ctx);
        mDialog.setTitle("提示")
        .setMessage("操作失败，请退出系统重新登录");
        mDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
        mDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
        
        mDialog.setCancelable(true);
        mDialog.show();
    }
    
    protected boolean isNetWorkCanUse(){
    	ConnectivityManager mConnectivityManager = (ConnectivityManager) ctx
			  .getSystemService(Context.CONNECTIVITY_SERVICE); 
	  	boolean wifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
	  	boolean isMobile = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
	  	return wifi || isMobile;
  	}
    protected void loadImage(ImageView iv, String ImgUrl) {
        Bitmap bitmap = asyncBitmapLoader.loadBitmap(iv, ImgUrl, new ImageCallBack() {  
            public void imageLoad(ImageView imageView, Bitmap bitmap) { 
                imageView.setImageBitmap(bitmap);  
            }  
        });  
		if(bitmap == null) {    
			iv.setImageResource(R.drawable.ic_launcher);    
		} else {    
			iv.setImageBitmap(bitmap);    
		}
	}
    protected String getString(JSONObject jo, String value) {
		try {
			return jo.getString(value);
		} catch (JSONException e) {
			Log.e(TAG, "getJSONObject", e);
		} catch(Exception e) {
			Log.e(TAG, "getJSONObject", e);
		}
		return null;
	}
    protected JSONObject getJSONObject(JSONObject jo, String value) {
		try {
			return jo.getJSONObject(value);
		} catch (JSONException e) {
			Log.e(TAG, "getJSONObject", e);
		} catch(Exception e) {
			Log.e(TAG, "getJSONObject", e);
		}
		return null;
	}
    protected JSONObject getJSONObject(JSONArray jList, int index) {
		try {
			return jList.getJSONObject(index);
		} catch (JSONException e) {
			Log.e(TAG, "getJSONObject", e);
		} catch(Exception e) {
			Log.e(TAG, "getJSONObject", e);
		}
		return null;
	}
    protected JSONArray getJSONArray(JSONObject jo, String value) {
		try {
			return jo.getJSONArray(value);
		} catch (JSONException e) {
			Log.e(TAG, "getJSONObject", e);
		} catch(Exception e) {
			Log.e(TAG, "getJSONObject", e);
		}
		return null;
	}
    protected JSONArray getJSONArray(JSONArray jList, int index) {
		try {
			return jList.getJSONArray(index);
		} catch (JSONException e) {
			Log.e(TAG, "getJSONObject", e);
		} catch(Exception e) {
			Log.e(TAG, "getJSONObject", e);
		}
		return null;
	}

	protected boolean IsValidEmail(String email) {
        boolean isValid = false;  
        String expression = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"; 
	    CharSequence inputStr = email;  
	    Pattern pattern = Pattern.compile(expression);  
	    Matcher matcher = pattern.matcher(inputStr);  
        isValid = matcher.matches();  
        return isValid;
    }
    protected boolean IsValidMobileNo(String MobileNo) {
    	boolean isValid = false;  
	    String expression = "^1[3|4|5|8][0-9]\\d{8}$";  
	    CharSequence inputStr = MobileNo;  
	    Pattern pattern = Pattern.compile(expression);  
	    Matcher matcher = pattern.matcher(inputStr);  
	    isValid = matcher.matches();  
	    return isValid;
    }
    protected boolean isPhoneNumberValid(String phoneNumber){  
	       boolean isValid = false;  
	       String expression = "^((13[0-9])|(15[^4,//D])|(18[0,5-9]))//d{8}$";  
	       String expression2 = "^((13[0-9])|(15[^4,//D])|(18[0,5-9]))//d{8}$";   
//	       String expression = "^/(?(/d{3})/)?[- ]?(/d{3})[- ]?(/d{5})$";  
//	       String expression2 = "^/(?(/d{3})/)?[- ]?(/d{4})[- ]?(/d{4})$";  
       	   CharSequence inputStr = phoneNumber;  
       	   Pattern pattern = Pattern.compile(expression);  
       	   Matcher matcher = pattern.matcher(inputStr);  
       	   Pattern pattern2 = Pattern.compile(expression2);  
       	   Matcher matcher2 = pattern2.matcher(inputStr);  
	       isValid = (matcher.matches()||matcher2.matches());  
	       return isValid;  
    		        
      }  
    protected void login() {
    	final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
	    waitDialog.setContentView(R.layout.login_dialog);
	//    waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
	//     waitDialog.setCancelable(false);
	    
	    //设置窗口里控件的透明度
	    Window window = waitDialog.getWindow();
	    WindowManager.LayoutParams wl = window.getAttributes();
	    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
	    wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
	    window.setAttributes(wl);
  
    	final EditText et_userName = (EditText)waitDialog.findViewById(R.id.login_dialog_username_et);
    	final EditText et_password = (EditText)waitDialog.findViewById(R.id.login_dialog_password_et);
    	et_userName.setText(userName);
    	et_password.setText(password);
    	et_userName.setSelection(userName.length());
    	et_password.setSelection(password.length());
    	Button login = (Button)waitDialog.findViewById(R.id.login_dialog_login_bt);
    	Button cancel = (Button)waitDialog.findViewById(R.id.login_dialog_cancel_bt);
    	Button register = (Button)waitDialog.findViewById(R.id.login_dialog_register_bt);
    	login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				userName = et_userName.getText().toString();
        		password = et_password.getText().toString();
        		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
        			showMessage(ctx, "用户名/密码不能为空！");
        		} else {
        			waitDialog.dismiss();
        			doLogin();
        		}
			}
		});
    	register.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ctx.setContentView(new RegisterWidget(ctx));
				waitDialog.dismiss();
			}
		});
    	cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				waitDialog.dismiss();
			}
		});
    	waitDialog.show();
	}
    private void doLogin() {
    	final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在登录...");
					break;
				case MessageWhat.LOGIN_SUCCESS:
					showMessage(ctx, "登陆成功");
					
					dismissMessageDialog();
					break;
				case MessageWhat.LOGIN_FAILD:
					dismissMessageDialog();
					String strMsg = (String)msg.obj;
					showMessage(ctx, strMsg);
					break;
				case MessageWhat.NETWORK_FAILD:
					dismissMessageDialog();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
    	handler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("username", userName));
				params.add(new BasicNameValuePair("userPassword", password));
				
				String response = HttpUtils.Post(Global.getServletlogin(),
						params);
				if (Global.DEBUG) {
					System.out.println("response" + response);
				}
				if (response != null) {
					try {
						JSONManager jsonManager = new JSONManager();
						if (jsonManager.isGotJSONObject2(response)) {
							User user = new User();
							JSONObject jsonObject = jsonManager.getJsonObject();
							// System.out.println(strReturn+"sucess");
							user.setUserId(jsonObject.getString("userid"));
							user.setUserName(jsonObject.getString("username"));
							user.setImgUrl(jsonObject.getString("headicon"));
							user.setSex(jsonObject.getString("gender"));
							
							user.setBirthDayTimeInMillis(1000*StringUtils.parseLong(jsonObject.getString("birthday")));
							user.setHeight(jsonObject.getString("height"));
							user.setWeight(jsonObject.getString("weight"));
							user.setCheckedBody(jsonObject.getString("physical"));
							
							user.setLabels(jsonObject.getString("tags"));
							user.setInfo(jsonObject.getString("intro"));
							user.setLevel(StringUtils.parseFloat(jsonObject.getString("level")));
							user.setProvince(jsonObject.getString("province"));
							user.setCity(jsonObject.getString("city"));
							user.seteMail(jsonObject.getString("email"));
							user.setRealName(jsonObject.getString("truename"));
							user.setTel(jsonObject.getString("mobile"));
							
							Global.user = user;
							handler.sendEmptyMessage(MessageWhat.LOGIN_SUCCESS);
						} else {
							Message msg = handler.obtainMessage(MessageWhat.LOGIN_FAILD, jsonManager.getMsg());
							msg.sendToTarget();
						}
					} catch (JSONException e) {
						Message msg = handler.obtainMessage(MessageWhat.LOGIN_FAILD, "登录失败！");
						msg.sendToTarget();
					}
				} else {
					handler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
    }
    /**
     * scrollview 内容始终显示在最低端
     * @param svResult
     */
    protected void setScrollViewDown(final ScrollView svResult) {
        svResult.post(new Runnable() {
            public void run() {
                svResult.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }
}
